package org.crazyit.activiti_d4._3_GetProcessGiagram;

import org.activiti.engine.ProcessEngine;
import org.activiti.engine.ProcessEngines;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.ProcessDefinition;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class GetProcessDiagram {

    public static void main(String[] args) {

        //1. 创建流程引擎
        ProcessEngine engine = ProcessEngines.getDefaultProcessEngine();

        //2. 得到流程存储服务引擎
        RepositoryService repositoryService = engine.getRepositoryService();

        //3. 部署一份流程文件与相应的流程图文件
        Deployment dep = repositoryService.createDeployment()
                .addClasspathResource("getProcessDiagram.bpmn")
                .addClasspathResource("getProcessDiagram.png")
                .deploy();

        try {

            //4. 查询流程定义
            ProcessDefinition def = repositoryService.createProcessDefinitionQuery().deploymentId(dep.getId()).singleResult();

            //5. 查询资源文件
            InputStream is = repositoryService.getProcessDiagram(def.getId());

            //6. 将输入流转换为图片对象
            BufferedImage image = ImageIO.read(is);

            //6. 保存为图片文件
            File file = new File("result.png");
            if (!file.exists()) {
                file.createNewFile();
            }
            FileOutputStream fos = new FileOutputStream(file);
            ImageIO.write(image,"png",fos);

            //7. 关闭IO 流
            is.close();
            fos.close();

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}
